<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    centered
    :title="displayModuleTitle"
    width="800px"
  >
    <a-steps size="small" :current="currentStep">
      <template v-if="showUnitDivisionTable">
        <a-step title="任务基本信息"></a-step>
        <a-step title="任务执行目标单元"></a-step>
        <a-step title="任务检查表"></a-step>
        <a-step title="预览"></a-step>
      </template>
      <template v-else
        ><a-step title="任务基本信息"></a-step>
        <a-step title="任务检查表"></a-step>
        <a-step title="预览"></a-step>
      </template>
    </a-steps>
    <div class="steps-content" style="display: flex; margin-top: 15px">
      <BasicForm @register="registerForm" style="flex: 1" v-show="currentStep == 0">
        <template #planfrequencycount="{ model, field }"
          ><span style="margin: 0 5px">至少执行</span>
          <a-input-number v-model:value="model[field]" :min="1" /><span style="margin-left: 5px"
            >次，</span
          >
        </template>
        <template #plantotalcount="{ model, field }"
          ><span>共计</span> <a-input-number v-model:value="model[field]" :min="1" /><span
            style="margin-left: 5px"
            >次。</span
          >
        </template>
        <template #planbegintm="{ model, field }">
          <a-radio-group
            v-model:value="choosetmType"
            style="margin: 0 5px 5px 0"
            button-style="solid"
            @change="(e) => changeChooseTm(e, model)"
          >
            <a-radio-button value="1">本月</a-radio-button>
            <a-radio-button value="2">本季度</a-radio-button>
            <a-radio-button value="4">本年</a-radio-button>
            <a-radio-button value="5">自定义</a-radio-button>
          </a-radio-group>
          <div style="display: flex">
            <a-button v-if="choosetmType != '5'" @click="tmRangeUpOrDown(model[field], 'before')">
              <template #icon><LeftOutlined /></template>上一{{
                choosetmType == '1' ? '月' : choosetmType == '2' ? '季度' : '年'
              }}</a-button
            >
            <a-range-picker
              :disabled="choosetmType != '5'"
              @change="(e) => generateTitles(e, 'tm')"
              v-model:value="model[field]"
              valueFormat="YYYY-MM-DD"
              :allowClear="false"
              style="width: 250px"
            />
            <a-button v-if="choosetmType != '5'" @click="tmRangeUpOrDown(model[field], 'after')"
              ><template #icon><RightOutlined /></template>下一{{
                choosetmType == '1' ? '月' : choosetmType == '2' ? '季度' : '年'
              }}</a-button
            >
          </div>
        </template>
      </BasicForm>
      <BasicTable
        v-show="showUnitDivisionTable && currentStep == 1"
        title="选择本次任务执行目标单元"
        @register="registerUnitTable"
        style="width: 100%; margin-right: 12px"
        @fetch-success="onFetchSuccess"
        :scroll="{ x: false, y: '320px' }"
      >
        <template #toolbar> 已选中 {{ getUnitSelectRowKeys().length }} 个 </template>
        <template #uccd="{ column, record }">
          {{ returnCategoryName(record.uccd, unitCategoryData) }}
        </template>
      </BasicTable>
      <div
        v-show="
          (showUnitDivisionTable && currentStep == 2) ||
          (!showUnitDivisionTable && currentStep == 1)
        "
      >
        <div>
          是否需要填写检查表：
          <a-radio-group v-model:value="needchecktable" name="radioGroup">
            <a-radio :value="true">是</a-radio>
            <a-radio :value="false">否</a-radio>
          </a-radio-group>
        </div>
        <div class="chooseCheckForm" style="margin-top: 10px" v-if="needchecktable">
          <a-alert
            message="请从下方已配置的检查表模板中选择一个或多个检查表。如没有需要填写的检查表模板，请联系管理员进行添加。"
            type="info"
            style="width: 99%"
            show-icon
          />
          <BasicTable
            @register="registerCheckFormTable"
            :pagination="false"
            :data-source="checkFormTableData"
            :scroll="{ x: false, y: '400px' }"
          >
            <template #toolbar>
              <div v-if="needchecktable === true">
                已选择{{ getCheckFormSelectRowKeys()?.length }}个检查表
              </div></template
            >
            <template #catcode="{ record }"
              >{{ categoryOption.find((item) => item.value == record.catcode)?.label }}
            </template>
          </BasicTable>
        </div>
      </div>
      <div
        v-show="
          (showUnitDivisionTable && currentStep == 3) ||
          (!showUnitDivisionTable && currentStep == 2)
        "
        class="preview"
      >
        <a-alert
          type="warning"
          style="margin: 8px 0"
          show-icon
          v-if="previewData?.msg"
          :message="previewData?.msg"
        />
        <BasicTable
          @register="registerPreviewTable"
          :pagination="false"
          :data-source="previewData?.tableData ?? []"
          :scroll="{ x: false, y: '300px' }"
          v-if="showUnitDivisionTable"
        >
        </BasicTable>
        <div style="flex: 1; width: 100%" v-else>
          <a-list
            size="small"
            bordered
            style="width: 100%; margin: 10px"
            :data-source="previewData?.groups ?? []"
            v-if="previewData?.groups"
          >
            <template #renderItem="{ item }">
              <a-list-item>{{ item }}</a-list-item>
            </template>
            <template #header>
              <div>分组集合</div>
            </template>
          </a-list>
          <a-alert
            type="warning"
            show-icon
            style="margin: 8px 0"
            v-if="!previewData?.groups && dataId"
            message="任务当前没有分组"
          />
          <a-list
            size="small"
            bordered
            :data-source="previewData?.checktables ?? []"
            style="width: 100%; margin: 10px"
          >
            <template #renderItem="{ item }">
              <a-list-item>{{ item }}</a-list-item>
            </template>
            <template #header>
              <div>检查表集合</div>
            </template>
          </a-list>
          <a-alert
            type="warning"
            show-icon
            style="margin: 8px 0"
            v-if="!previewData?.checktables"
            message="任务没有选择检查表"
          />
        </div>
      </div>
    </div>
    <template #footer>
      <template v-if="showUnitDivisionTable">
        <a-button @click="currentStep--" v-if="currentStep > 0">上一步</a-button>
        <a-button
          @click="onButtonOkClick"
          type="primary"
          v-if="currentStep == 3 && previewData?.isok"
          >保存任务</a-button
        >
        <a-button
          @click="
            if (currentStep == 2) getPreviewData();
            else currentStep++;
          "
          v-if="currentStep < 3"
          >下一步</a-button
        >
      </template>
      <template v-else>
        <a-button @click="currentStep--" v-if="currentStep > 0">上一步</a-button>
        <a-button
          @click="onButtonOkClick"
          type="primary"
          v-if="currentStep == 2 && previewData?.isok"
          >保存任务</a-button
        >
        <a-button
          @click="
            if (currentStep == 1) getPreviewData();
            else currentStep++;
          "
          v-if="currentStep < 2"
          >下一步</a-button
        >
      </template>
      <a-button @click="closeModal">取消</a-button>
    </template>
    <Loading :loading="loading" tip="加载中" />
  </BasicModal>
</template>

<script lang="ts">
  import { defineComponent, ref, unref, computed, onMounted, nextTick, watch, h } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { queryEnumOption } from '/@/api/qms/exchangeData';
  import {
    addOrUpdateTaskFormSchema,
    unitDivisionTableColumns,
    previewTableColumns,
  } from './taskConsole.data';
  import { addTask, getTaskInfo, updateTask } from '/@/api/ehs/task';
  import { getAllTaskCategory } from '/@/api/ehs/taskCategory';
  import { getUserOrganization } from '/@/api/ehs/organization';
  const { createMessage } = useMessage();
  import { useGlobSetting } from '/@/hooks/setting';
  const { globalProjectCode } = useGlobSetting();
  import { getTaskGroupObjects, setTaskGroups, previewTask } from '/@/api/ehs/task';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { queryUnitDivision } from '/@/api/ehs/unitDivision';
  import { queryUnitCategory } from '/@/api/ehs/unitCategory';
  import { LeftOutlined, RightOutlined } from '@ant-design/icons-vue';
  import { Loading } from '/@/components/Loading';
  import { chooseFormColumns, chooseFormTableCondition } from '../checkForm/checkForm.data';
  import { queryCheckForm } from '/@/api/ehs/checkForm';
  import moment from 'moment';
  import { load } from '@amap/amap-jsapi-loader';
  import { preview } from 'vite';
  export default defineComponent({
    name: 'AddOrUpdateTask',
    components: { BasicModal, BasicForm, BasicTable, LeftOutlined, RightOutlined, Loading },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      //弹出窗口界面是新增数据、修改数据；根据传递过来的参数进行判断
      const operateType = ref(OperationTypeEnum.UN_KNOWN);
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const dataId = ref<String>('');
      const orgcode = ref<String>('');
      const projectCode = ref<String>(globalProjectCode);
      const showUnitDivisionTable = ref(false);
      const needchecktable = ref(true);
      const currentStep = ref(0);
      const unitCategoryData = ref([]);
      const categoryOption = ref([]);
      const checkFormTableData = ref();
      const choosetmType = ref('4');
      const loading = ref(false);
      const previewData = ref({});
      const [
        registerForm,
        { setFieldsValue, resetFields, getFieldsValue, validate, clearValidate, updateSchema },
      ] = useForm({
        labelWidth: 120,
        schemas: addOrUpdateTaskFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      const [
        registerUnitTable,
        {
          setSelectedRowKeys: setUnitSelectRowKeys,
          getSelectRowKeys: getUnitSelectRowKeys,
          clearSelectedRowKeys: clearUnitSelectedRowKeys,
          expandAll: expandAllUnit,
          reload: reloadUnit,
        },
      ] = useTable({
        api: queryUnitDivision,
        columns: unitDivisionTableColumns,
        canResize: true,
        striped: false,
        showTableSetting: false,
        showIndexColumn: false,
        isTreeTable: true,
        bordered: true,
        ellipsis: true,
        immediate: false,
        size: 'small',
        useSearchForm: false,
        beforeFetch: (params) => {
          return { includechilds: true, isdept: false, flagisvalid: true, orgcode: orgcode.value };
        },
        pagination: false,
        rowSelection: {
          type: 'checkbox',
        },
        rowKey: 'unitid',
      });

      const [
        registerCheckFormTable,
        {
          getSelectRowKeys: getCheckFormSelectRowKeys,
          setSelectedRowKeys: setCheckFormSelectRowKeys,
          clearSelectedRowKeys: clearCheckFormSelectedRowKeys,
        },
      ] = useTable({
        columns: chooseFormColumns,
        canResize: true,
        striped: true,
        showTableSetting: false,
        immediate: false,
        showIndexColumn: true,
        isTreeTable: false,
        bordered: true,
        ellipsis: true,
        rowSelection: { type: 'checkbox' },
        rowKey: 'tableid',
      });

      const [registerPreviewTable, {}] = useTable({
        columns: previewTableColumns,
        canResize: true,
        striped: false,
        showTableSetting: false,
        showIndexColumn: false,
        isTreeTable: true,
        bordered: true,
        ellipsis: true,
        size: 'small',
        useSearchForm: false,
      });

      /**
       * 根据父组件传递过来的参数获取对应的操作，操作不同所对应的界面不同
       */
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        loading.value = true;
        dataId.value = null;
        resetFields(); //重置表单
        clearUnitSelectedRowKeys();
        clearCheckFormSelectedRowKeys();
        currentStep.value = 0;
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          //接收父组件传递的数据
          if (unrefData?.operateType) {
            //判断是否传入op属性
            operateType.value = unrefData.operateType;
          }
          if (unrefData?.dataId) {
            dataId.value = unrefData.dataId;
          }
        }
        getUserOrganization(projectCode.value).then((res0) => {
          orgcode.value = res0.orgcode;
          reloadUnit();
          getAllTaskCategory(orgcode.value).then((res) => {
            categoryOption.value = res
              ? res.map((item) => {
                  return {
                    ...item,
                    label: item.catname,
                    value: item.catcode,
                  };
                })
              : [];
            updateSchema([
              {
                field: 'catname',
                componentProps: {
                  allowClear: false,
                  options: res.map((option) => {
                    return {
                      value: option.catname,
                      label: option.catname,
                    };
                  }),
                  onChange: (e) => {
                    let tmp = res.find((item) => item.catname == e);
                    console.log(e, tmp, res);
                    showUnitDivisionTable.value = tmp?.tasktype == 8 ? false : true;
                    choosetmType.value = tmp?.tasktype == 8 ? '5' : '4';
                    queryCheckForm({
                      orgcode: orgcode.value,
                      catcode: tmp.catcode,
                      status: 0,
                    }).then((res) => {
                      clearCheckFormSelectedRowKeys();
                      if (res) checkFormTableData.value = res;
                      else checkFormTableData.value = [];
                    });
                    setFieldsValue({
                      tasktype: tmp?.tasktype,
                      type: tmp?.tasktype == 8 ? 2 : 1,
                      planfrequencytype: tmp?.tasktype == 8 ? 0 : 6,
                      planbegintm:
                        tmp?.tasktype == 8
                          ? [
                              moment().format('YYYY-MM-DD'),
                              moment().add(7, 'days').format('YYYY-MM-DD'),
                            ]
                          : [
                              moment().startOf('year').format('YYYY-MM-DD'),
                              moment().endOf('year').format('YYYY-MM-DD'),
                            ],
                      objtype: tmp?.objecttype,
                      notnull: tmp?.notnull,
                      needsignin: tmp?.needsignin,
                      // needchecktable: tmp?.needchecktable,
                      needconfirm: tmp?.needconfirm,
                    });
                    needchecktable.value = tmp?.needchecktable;
                    generateTitles(
                      e,
                      'all',
                      tmp?.tasktype == 8
                        ? [
                            moment().format('YYYY-MM-DD'),
                            moment().add(7, 'days').format('YYYY-MM-DD'),
                          ]
                        : [
                            moment().startOf('year').format('YYYY-MM-DD'),
                            moment().endOf('year').format('YYYY-MM-DD'),
                          ],
                    );
                  },
                },
              },
              {
                field: 'type',
                componentProps: {
                  onChange: (e) => {
                    choosetmType.value = e == 2 ? '5' : '4';
                    setFieldsValue({
                      planbegintm:
                        e == 2
                          ? [
                              moment().format('YYYY-MM-DD'),
                              moment().add(7, 'days').format('YYYY-MM-DD'),
                            ]
                          : [
                              moment().startOf('year').format('YYYY-MM-DD'),
                              moment().endOf('year').format('YYYY-MM-DD'),
                            ],
                    });
                  },
                  options: [
                    {
                      label: '定期/频率任务',
                      value: 1,
                    },
                    {
                      label: '单次/临时任务',
                      value: 2,
                    },
                  ],
                },
              },
            ]);
            // 如果是修改数据，根据传入的id获取数据后进行赋值

            if (operateType.value == OperationTypeEnum.EDIT) {
              getTaskInfoById();
              choosetmType.value = '5';
              loading.value = false;
            } else {
              setFieldsValue({
                tasktitle: moment().format('YYYY年') + res[0].catname,
                catname: res[0].catname,
                tasktype: res[0]?.tasktype,
                objtype: res[0]?.objecttype,
                notnull: res[0]?.notnull,
                needsignin: res[0]?.needsignin,
                // needchecktable: res[0]?.needchecktable,
                needconfirm: res[0]?.needconfirm,
              });
              needchecktable.value = res[0].needchecktable;
              queryCheckForm({ orgcode: orgcode.value, catcode: res[0].catcode, status: 0 }).then(
                (res) => {
                  clearCheckFormSelectedRowKeys();
                  if (res) checkFormTableData.value = res;
                  else checkFormTableData.value = [];
                },
              );
              showUnitDivisionTable.value = res[0]?.tasktype == 8 ? false : true;
              choosetmType.value = '4';
              loading.value = false;
            }
          });
        });
        queryEnumOption(
          'EhsTaskDestObjectTypeEnum,TimeRangeLengthEnum,EhsTaskCategoryTypeEnum',
        ).then((res) => {
          let objOptions = [];
          for (let i of res[0].options) {
            objOptions.push({ value: Number(i.key), label: i.value });
          }
          let timeOptions = [];
          for (let i of res[1].options) {
            timeOptions.push({ value: Number(i.key), label: i.value });
          }
          let tasktypeOp = res[2].options.map((option) => {
            return {
              value: Number(option.key),
              label: option.value,
            };
          });
          updateSchema([
            {
              field: 'objtype',
              componentProps: {
                options: objOptions,
                listHeight: 200,
                getPopupContainer: (triggerNode) => document.body,
              },
            },
            {
              field: 'tasktype',
              componentProps: {
                options: tasktypeOp,
                listHeight: 200,
                getPopupContainer: (triggerNode) => document.body,
              },
            },
          ]);
        });
      });

      function onFetchSuccess() {
        nextTick(expandAllUnit);
      }

      // 快捷选择日期配置
      function changeChooseTm(e, model) {
        let op = {
          1: [
            moment().startOf('month').format('YYYY-MM-DD'),
            moment().endOf('month').format('YYYY-MM-DD'),
          ],
          2: [
            moment().startOf('quarter').format('YYYY-MM-DD'),
            moment().endOf('quarter').format('YYYY-MM-DD'),
          ],
          4: [
            moment().startOf('year').format('YYYY-MM-DD'),
            moment().endOf('year').format('YYYY-MM-DD'),
          ],
        };
        if (e.target.value != '5') {
          setFieldsValue({
            planbegintm: op[e.target.value],
          });
          generateTitles(op[e.target.value], 'tm');
        }
        clearValidate();
      }

      // 日期上一个下一个周期切换
      function tmRangeUpOrDown(tm, type) {
        let resulttm = [];
        if (choosetmType.value == 1) {
          // 上一个或下一个月份
          if (type == 'before') {
            resulttm = [
              moment(tm[0]).subtract(1, 'months').startOf('month').format('YYYY-MM-DD'),
              moment(tm[1]).subtract(1, 'months').endOf('month').format('YYYY-MM-DD'),
            ];
          } else {
            resulttm = [
              moment(tm[0]).add(1, 'months').startOf('month').format('YYYY-MM-DD'),
              moment(tm[1]).add(1, 'months').endOf('month').format('YYYY-MM-DD'),
            ];
          }
        } else if (choosetmType.value == 2) {
          // 上一个下一个季度
          if (type == 'before') {
            resulttm = [
              moment(tm[0]).subtract(1, 'quarters').startOf('month').format('YYYY-MM-DD'),
              moment(tm[1]).subtract(1, 'quarters').endOf('month').format('YYYY-MM-DD'),
            ];
          } else {
            resulttm = [
              moment(tm[0]).add(1, 'quarters').startOf('month').format('YYYY-MM-DD'),
              moment(tm[1]).add(1, 'quarters').endOf('month').format('YYYY-MM-DD'),
            ];
          }
        } else if (choosetmType.value == 4) {
          // 上一年下一年
          if (type == 'before') {
            resulttm = [
              moment(tm[0]).subtract(1, 'years').startOf('month').format('YYYY-MM-DD'),
              moment(tm[1]).subtract(1, 'years').endOf('month').format('YYYY-MM-DD'),
            ];
          } else {
            resulttm = [
              moment(tm[0]).add(1, 'years').startOf('month').format('YYYY-MM-DD'),
              moment(tm[1]).add(1, 'years').endOf('month').format('YYYY-MM-DD'),
            ];
          }
        }
        generateTitles(resulttm, 'tm');
        setFieldsValue({
          planbegintm: resulttm,
        });
      }

      /**
       * 返回弹窗标题
       */
      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      /**
       * 根据id获取静态信息
       */
      async function getTaskInfoById() {
        getTaskInfo(dataId.value)
          .then((res) => {
            queryCheckForm({
              orgcode: orgcode.value,
              catcode: categoryOption.value.find((item) => item.catname == res.catname).catcode,
              status: 0,
            }).then((res) => {
              clearCheckFormSelectedRowKeys();
              if (res) checkFormTableData.value = res;
              else checkFormTableData.value = [];
            });
            console.log('res', res);
            getTaskGroupObjects(dataId.value)
              .then((res2) => {
                showUnitDivisionTable.value = res?.tasktype == 8 ? false : true;
                setFieldsValue({
                  ...res,
                  planbegintm: [res.planbegintm, res.planendtm],
                  taskattachment: res.taskattachment ? JSON.parse(res.taskattachment) : [],
                  type: res.planfrequencytype == 0 ? 2 : 1,
                });
                if (showUnitDivisionTable.value) {
                  setUnitSelectRowKeys(res2.objectids);
                }
                if (res.checktableids) setCheckFormSelectRowKeys(res.checktableids);
                loading.value = false;
              })
              .catch((ex) => {
                console.log('catch ', ex);
                // createMessage.error(ex.msg);
                loading.value = false;
              });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
            loading.value = false;
          });
      }
      /**
       * 点击确认按钮，根据不同的op调用对应方法保存信息
       */
      async function onButtonOkClick() {
        let values;
        try {
          values = await validate();
        } catch (e) {
          createMessage.error('请检查表单信息是否填写完整');
          currentStep.value = 0;
          return;
        }
        loading.value = true;
        console.log(values, 'value');
        values.orgcode = orgcode.value;
        values.needchecktable = needchecktable.value;
        if (values.type == 2) {
          values.planfrequencytype = 0;
          values.planfrequencycount = 1;
          values.plantotalcount = 1;
        }
        values.planfrequencycount = values?.planfrequencycount ?? 1;
        values.plantotalcount = values?.plantotalcount ?? 1;
        values.planendtm = values.planbegintm[1];
        values.planbegintm = values.planbegintm[0];
        values.taskattachment = JSON.stringify(values.taskattachment);

        if (showUnitDivisionTable.value) {
          values.groupobjids = getUnitSelectRowKeys();
          if (getUnitSelectRowKeys().length == 0) {
            loading.value = false;
            return createMessage.error('请选择任务执行目标单元');
          }
        } else {
          values.groupobjids = [];
        }

        if (needchecktable.value) {
          values.checktableids = getCheckFormSelectRowKeys();
          if (getCheckFormSelectRowKeys().length == 0) {
            loading.value = false;
            return createMessage.error('请选择任务执行填写的检查表');
          }
        } else {
          values.checktableids = [];
        }
        //根据指定的操作类型分别进行提交数据和处理
        if (operateType.value == OperationTypeEnum.ADD) {
          //对应操作的步骤为：验证表单、提交后台保存、关闭modal、调用父组件事件刷新数据
          try {
            //调用接口进行保存
            addTask({ ...values })
              .then((res) => {
                if (!res || Object.keys(res).length == 0) {
                  createMessage.success('保存成功。', 4);
                  opSuccess();
                } else {
                  createMessage.error('创建失败' + res, 4);
                }
                loading.value = false;
              })
              .catch((ex) => {
                console.log('catch ', ex);
                createMessage.error(ex.msg);
                loading.value = false;
              });
          } finally {
            loading.value = false;
          }
        } else if (operateType.value == OperationTypeEnum.EDIT) {
          //调用接口进行保存
          updateTask({ ...values, taskid: dataId.value })
            .then((res) => {
              if (!res || Object.keys(res).length == 0) {
                if (values.tasktype == 1 || values.tasktype == 2 || values.tasktype == 16) {
                  createMessage.success('修改成功。', 2);
                  loading.value = false;
                  opSuccess();
                  setTaskGroups({
                    taskid: dataId.value,
                    groupobjtype: 1,
                    groupobjids: getUnitSelectRowKeys(),
                  })
                    .then((res) => {
                      createMessage.success('修改成功。', 2);
                      loading.value = false;
                      opSuccess();
                    })
                    .catch((ex) => {
                      console.log('catch ', ex);
                      loading.value = false;
                      createMessage.error(ex.msg);
                    });
                } else {
                  createMessage.success('修改成功。', 2);
                  loading.value = false;
                  opSuccess();
                }
              }
            })
            .catch((ex) => {
              console.log('catch ', ex);
              loading.value = false;
            });
        } else {
          createMessage.error('当前操作类型错误，无法进行对应操作。', 5);
        }
      }

      function returnCategoryName(uccd, unitCategory) {
        for (let i = 0; i < unitCategory.length; i++) {
          let a = unitCategory[i];
          if (a.uccd == uccd) {
            return a.ucnm;
          } else {
            if (a.children && a.children.length > 0) {
              let res = returnCategoryName(uccd, a.children);
              if (res) {
                return res;
              }
            }
          }
        }
        return uccd;
      }

      //操作成功后
      function opSuccess() {
        emit('success');
        closeModal();
      }

      /**
       * 获取预览数据
       */
      async function getPreviewData() {
        let values;
        try {
          values = await validate();
        } catch (e) {
          createMessage.error('请检查表单信息是否填写完整');
          currentStep.value = 0;
          return;
        }
        loading.value = true;
        console.log(values, 'value');
        values.orgcode = orgcode.value;
        values.needchecktable = needchecktable.value;
        if (values.type == 2) {
          values.planfrequencytype = 0;
          values.planfrequencycount = 1;
          values.plantotalcount = 1;
        }
        values.planfrequencycount = values?.planfrequencycount ?? 1;
        values.plantotalcount = values?.plantotalcount ?? 1;
        values.planendtm = values.planbegintm[1];
        values.planbegintm = values.planbegintm[0];
        values.taskattachment = JSON.stringify(values.taskattachment);

        if (showUnitDivisionTable.value) {
          values.groupobjids = getUnitSelectRowKeys();
          if (getUnitSelectRowKeys().length == 0) {
            loading.value = false;
            return createMessage.error('请选择任务执行目标单元');
          }
        } else {
          values.groupobjids = [];
        }
        if (needchecktable.value) {
          values.checktableids = getCheckFormSelectRowKeys();
          if (getCheckFormSelectRowKeys().length == 0) {
            loading.value = false;
            return createMessage.error('请选择任务执行填写的检查表');
          }
        } else {
          values.checktableids = [];
        }
        previewTask({ ...values, taskid: dataId.value })
          .then((res) => {
            previewData.value = res;
            previewData.value.tableData = [];
            console.log(previewData.value, 'resres');
            if (res?.units && res?.units?.length > 0) {
              for (let i = 0; i < res.units.length; i++) {
                previewData.value.tableData[i] = {
                  unit: res.units[i],
                  checkForm: res.unitchecktables[i],
                };
              }
            }
            loading.value = false;
            currentStep.value = currentStep.value + 1;
          })
          .catch((err) => {
            console.log(err, 'err');
            loading.value = false;
            createMessage.error('获取预览数据失败,请稍后重试');
          });
      }

      /**
       *
       * @param e 生成任务标题
       * @param type
       * @param e2
       */
      function generateTitles(e, type, e2) {
        let model = getFieldsValue();
        if (type == 'tm') {
          model.planbegintm = e;
        } else if (type == 'type') {
          model.catname = e;
        } else {
          model.catname = e;
          model.planbegintm = e2;
        }
        console.log('change', choosetmType.value, model, model.planbegintm);
        let title = '';
        if (choosetmType.value == '1') {
          title = moment(model.planbegintm[0]).format('YYYY年MM月') + model.catname;
        } else if (choosetmType.value == '2') {
          title = moment(model.planbegintm[0]).format('YYYY年第Q季度') + model.catname;
        } else if (choosetmType.value == '4') {
          title = moment(model.planbegintm[0]).format('YYYY年') + model.catname;
        } else {
          title =
            moment(model.planbegintm[0]).format('YYYY年MM月DD日') +
            '至' +
            moment(model.planbegintm[1]).format('YYYY年MM月DD日') +
            model.catname;
        }
        setFieldsValue({
          tasktitle: title,
        });
      }

      watch(
        () => needchecktable.value,
        (newval) => {
          if (newval) {
            let model = getFieldsValue();
            let code = categoryOption.value.find((item) => item.label == model.catname).catcode;
            queryCheckForm({ orgcode: orgcode.value, catcode: code, status: 0 }).then((res) => {
              if (res) checkFormTableData.value = res;
              else checkFormTableData.value = [];
            });
          }
          clearCheckFormSelectedRowKeys();
        },
      );

      onMounted(() => {
        queryUnitCategory()
          .then((res) => {
            unitCategoryData.value = res;
          })
          .catch((e) => {});
      });
      return {
        h,
        dataId,
        loading,
        registerUnitTable,
        registerPreviewTable,
        registerCheckFormTable,
        choosetmType,
        currentStep,
        showUnitDivisionTable,
        needchecktable,
        operateType,
        displayModuleTitle,
        changeChooseTm,
        tmRangeUpOrDown,
        registerModal,
        registerForm,
        getTaskInfoById,
        onButtonOkClick,
        opSuccess,
        returnCategoryName,
        onFetchSuccess,
        unitCategoryData,
        categoryOption,
        getUnitSelectRowKeys,
        generateTitles,
        closeModal,
        getFieldsValue,
        checkFormTableData,
        getPreviewData,
        previewData,
        getCheckFormSelectRowKeys,
      };
    },
  });
</script>

<style scoped></style>
